package autoz.czt.wizards;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbench;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;

import autoz.czt.wizards.pages.MainPage;
import autoz.core.wizards.AbstractNewProjectWizard;

public class NewProjectWizard extends AbstractNewProjectWizard {

	MainPage mainPage;

	/**
	 * Constructor for NewProjectWizard.
	 */
	public NewProjectWizard() {
		super();
	}

	/**
	 * Add dialog pages to the wizard.
	 */
	public void addPages() {
		mainPage = new MainPage(model);
		addPage(mainPage);
	}

	/**
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.workbench = workbench;
		this.selection = selection;
	}

	/**
	 * Display the finish button (or not).
	 */
	public boolean canFinish() {
		// As there is only one page, this can finish.
		// TODO check that everything has a correctly assigned value
		return true;
	}

	/**
	 * Action performed on clicking the finish button.
	 */
	public boolean performFinish() {
		NewProjectCreationOperation runnable = new NewProjectCreationOperation(model);
		IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(runnable);

		boolean result = true;
		try {

			getContainer().run(false, true, op);

		} catch (InterruptedException e) {
			result = false;
		} catch (InvocationTargetException e) {
			handleTargetException(e.getTargetException());
			result = false;
		}

		BasicNewProjectResourceWizard.updatePerspective(configElement);
		return result;
	}

	/**
	 * Handle the exceptions of project creation here.
	 * 
	 * @param target
	 */
	protected void handleTargetException(Throwable target) {

		MessageDialog.openError(getShell(), "Project Creation Error", target
				.getMessage());
	}

	public void setInitializationData(IConfigurationElement config,
			String propertyName, Object data) throws CoreException {
		configElement = config;

	}
}
